// WordSoupOCR.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "GridImage.h"
#include "Solver.h"

    

/*
WordSoup.exe.lnk grid4.jpg 60 60 330 490 999999
WordSoup.exe.lnk grid4.jpg 60 60 330 490 999999 40 160

WordSoup.exe.lnk New\DSC00046.jpg 60 60 330 490 999999 40 160

WordSoup.exe.lnk New\DSC00046.jpg 15 60 330
WordSoup.exe.lnk New\DSC00046.jpg 100 0 700 1200
*/

#define MINSEP 15

GridImage image;
char WriteFolder[500];

void Draw(Grid * grid)
{
	image.Display(grid, WriteFolder);
}



/*
bool WatchFolder(char * Folder, char * ReturnS)
{
	int numfiles = 0,newfiles;


	sprintf_s(ReturnS, 500, "%s\\*.JPG", Folder);
	sprintf_s(WriteFolder, 500, "%s\\Solutions", Folder);
	

	char Command[500];
	sprintf_s(Command, 500, "rmdir /S /Q \"%s\"", WriteFolder);
	printf("Running: %s\n", Command);
	system(Command);
	sprintf_s(Command, 500, "mkdir \"%s\"", WriteFolder);
	system(Command);

	WIN32_FIND_DATAA findFileData;
    HANDLE hFind = FindFirstFileA(ReturnS, &findFileData);

	if(hFind  == INVALID_HANDLE_VALUE) {
		return 0;
    }

	while(FindNextFileA(hFind, &findFileData))
		numfiles++;

	while(true)
	{
		Sleep(1000);
		newfiles = 0;

		hFind = FindFirstFileA(ReturnS, &findFileData);
		if(hFind  == INVALID_HANDLE_VALUE) {
			return 0;
		}

		while(FindNextFileA(hFind, &findFileData))
		{
			newfiles++;
			if (newfiles > numfiles)
			{
				sprintf_s(ReturnS, 500, "%s\\%s", Folder, findFileData.cFileName);
				return 1;
			}
		}
	}
}
*/

//int run(char * folder)
int main(int argc, char* argv[])
{
	//int allpoints = 0;
	Grid newgrid;

	//wtf am i doing?
	if (!Dictionary)
		Dictionary = new DictionaryTree("dictionary.txt");

	Dictionary->Start();


	if (!pSolve)
		pSolve = new Solver();

	pSolve->ratiomult = 2;
	pSolve->gtailmult = 3;
	pSolve->ltailmult = 0;
	pSolve->variable = 750;
	
	pSolve->pDraw = Draw;

	//char file[500];
	//GridImage image;
	char * file = argv[1];


	/*printf("Waiting for photo...\n");

	if (!WatchFolder(folder, file))
	{
		printf("Folder error\n");
		return 0;
	}
	
	printf("Detected: %s\n", file);

	//Sleep(1000);

	while (1)
	{
		Sleep(1000);
		if (image.OpenFile(file))
			break;
	}
	*/

	if (!image.OpenFile(file))
	{
		printf("Could not open: %s\n", file);	
		return 0;
	}

	printf("Opened: %s\n", file);

	image.Smooth();
	//image.Smooth();

	CvPoint start;
	CvScalar c;

	for (start.y = 0; start.y < image.sz.height; start.y++)
	for (start.x = 0; start.x < image.sz.width; start.x++)
	{
		c = cvGetAt(image.hsv,start.y,start.x);

		if (c.val[1] <= 40 && c.val[2] >= 140)
		{
			cvLine( image.let, start, start, CV_RGB(255,255,255), 1, 8 );
		}
	}

	cvSaveImage("Letters.JPG", image.let);

	char characs[130];

	printf("Scanning...\n");

	if (!image.GetCharacters(characs))
	{
		cvSaveImage("Failed.JPG", image.src);
		cvSaveImage("Draw.JPG", image.draw);
		printf("Could not get characters...\n");
		
		return 0;
		//printf("Using characters...\n");
		//sprintf_s(characs, 129, "UOIIESLNEJSWTAVHPPTEZKTOOANASAORFMIRAILOCLBTIEMBTIAEOYVNIJUDDPAERUNPJOTBBEEJSREZWMURWLTEIRABGOITNBNWLRUASIETDIHEDFAIO");
	}

	cvSaveImage("Draw.JPG", image.draw);

	printf("Found!: %s\n", characs);

	/*printf("Compare to:");

	int errors = 0;
	int mistakes = 0;
	char comptext[130];

	scanf_s("%s", comptext, 130);

	for (int c=0;c<117;++c)
	{
		if (characs[c] == '?')
		{
			errors++;
			continue;
		}

		if (characs[c] != comptext[c])
			mistakes++;
	}

	printf("E,M,T: %d, %d, %d\n", errors, mistakes, End-Start);

	return 0;*/

	//return 0;
	
	/*CvSize smz;
	smz.height = image.sz.height / 4;
	smz.width = image.sz.width / 4;
	
	IplImage* display = cvCreateImage( smz, 8, 3 );

	cvResize(image.draw, display);
	cvNamedWindow( "Hough" );
    cvShowImage( "Hough", display );*/

	newgrid.GetGrid(characs);
	
	pSolve->Solve(&newgrid);

	return 0;
}

/*
int main3(int argc, char* argv[])
{
	while (1)
	{
		printf("Starting...\n");

		int ret = run(argv[1]);

		Sleep(120000);

		printf("Looping...\n");
	}
}
*/
int main2(int argc, char* argv[])
{
	IplImage* src;

    if((src=cvLoadImage(argv[1], 1))!= 0)
    {
		CvSize sz = cvGetSize(src);

		IplImage* med = cvCreateImage( sz, 8, 3 );
		IplImage* medgrey = cvCreateImage( sz, 8, 1 );
		IplImage* dsth = cvCreateImage( sz, 8, 1 );
		IplImage* dstv = cvCreateImage( sz, 8, 1 );
        IplImage* color_dst = cvCreateImage( sz, 8, 3 );
		sz.width += 2;
		sz.height += 2;
		IplImage* mask = cvCreateImage( sz,  IPL_DEPTH_8U, 1 );
		sz.width -= 2;
		sz.height -= 2;
		sz.height = sz.height / 4;
		sz.width = sz.width / 4;
		IplImage* color_dst2 = cvCreateImage( sz, 8, 3 );

		cvZero(mask);

        CvMemStorage* storage = cvCreateMemStorage(0);
        CvSeq* lines = 0;
        int i;

		//dst->

		
		//cvCvtColor(src,dst);

		//cvLaplace(src,dst,3);

		cvCopyImage(src, color_dst);
		

		//cvSobel(src, med, 1, 0);
		//cvCopyImage(src, med);
		cvSmooth(src,med,2,7);
		cvSmooth(med,med,2,5);
		cvSmooth(med,med,2,3);
		
		cvSobel(med, med, 1, 0);
		cvCvtColor( med, medgrey, CV_BGR2GRAY );
		//cvCopyImage(med, src);
		cvThreshold( medgrey, medgrey, atof(argv[2]), 255, CV_THRESH_BINARY );

		cvCopyImage(medgrey, dsth);
		
		cvSmooth(src,med,2,7);
		cvSmooth(med,med,2,5);
		cvSmooth(med,med,2,3);
		cvSobel(src, med, 0, 1);
		cvCvtColor( med, medgrey, CV_BGR2GRAY );
		cvThreshold( medgrey, medgrey, atof(argv[3]), 255, CV_THRESH_BINARY );



		cvCopyImage(medgrey, dstv);
		//cvResize(med,dst,1);

		cvThreshold( dstv, dstv, 50, 255, CV_THRESH_BINARY );
		cvThreshold( dsth, dsth, 50, 255, CV_THRESH_BINARY );
		
		//cvCanny( src, dst, atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) );

        //cvCvtColor( dstv, color_dst, CV_GRAY2BGR );
		//cvCvtColor( src, color_dst, CV_BGR2HSV );

		cvCvtColor( src, med, CV_BGR2HSV );

		//cvCopyImage(src, color_dst);

		//180,280				1039,282
		//173,723				1033,732

		if (true)
		{
			lines = cvHoughLines2( dstv, storage, CV_HOUGH_STANDARD, 2, (CV_PI/180), atoi(argv[5]), 0, 0 );

			std::vector<scrline> linelist;

			for( i = 0; i < MIN(lines->total,atoi(argv[6])); i++ )
			{
				float* line = (float*)cvGetSeqElem(lines,i);
				float rho = line[0];
				float theta = line[1];
				float addy = (float)(-CV_PI / 2);
				if ((theta + addy > 0.025) || (theta + addy < -00.025)) continue;

				double a = cos(theta), b = sin(theta);
				double x0 = a*rho, y0 = b*rho;

				CvPoint pt1, pt2;
				pt1.x = cvRound(x0 + 5000*(-b));
				pt1.y = cvRound(y0 + 5000*(a));
				pt2.x = cvRound(x0 - 5000*(-b));
				pt2.y = cvRound(y0 - 5000*(a));
				cvLine( color_dst, pt1, pt2, CV_RGB(255,0,0), 2, 8 );

				bool found = false;
				for (int l = 0; l < (int)linelist.size(); l++)
				{
					if ((rho < (linelist[l].rho + MINSEP)) && (rho > (linelist[l].rho - MINSEP)))
					{
						found = true;
						
						linelist[l].rho = (linelist[l].rho * linelist[l].avgs + rho) / (linelist[l].avgs + 1);
						linelist[l].theta = (linelist[l].theta * linelist[l].avgs + theta) / (linelist[l].avgs + 1);
						linelist[l].avgs++;

						break;
					}
				}

				if (!found)
				{
					scrline temp = {line[0],line[1],1};
					linelist.push_back(temp);
				}
			}

			for (int l = 0; l < (int)linelist.size(); l++)
			{
				
				double a = cos(linelist[l].theta), b = sin(linelist[l].theta);
				double x0 = a*linelist[l].rho, y0 = b*linelist[l].rho;
				
				//double a = cos(theta), b = sin(theta);
				//double x0 = a*rho, y0 = b*rho;

				CvPoint pt1, pt2;
				pt1.x = cvRound(x0 + 5000*(-b));
				pt1.y = cvRound(y0 + 5000*(a));
				pt2.x = cvRound(x0 - 5000*(-b));
				pt2.y = cvRound(y0 - 5000*(a));
				cvLine( color_dst, pt1, pt2, CV_RGB(0,255,0), 4, 8 );
			}

			
			lines = cvHoughLines2( dsth, storage, CV_HOUGH_STANDARD, 2, (CV_PI/180), atoi(argv[4]), 0, 0 );

			std::vector<scrline> linelist2;

			for( i = 0; i < MIN(lines->total,atoi(argv[6])); i++ )
			{
				float* line = (float*)cvGetSeqElem(lines,i);
				float rho = line[0];
				float theta = line[1];
				//float addy = (float)(-CV_PI / 2);
				if ((theta > 0.025) || (theta < -00.25)) continue;

				double a = cos(theta), b = sin(theta);
				double x0 = a*rho, y0 = b*rho;

				CvPoint pt1, pt2;
				pt1.x = cvRound(x0 + 5000*(-b));
				pt1.y = cvRound(y0 + 5000*(a));
				pt2.x = cvRound(x0 - 5000*(-b));
				pt2.y = cvRound(y0 - 5000*(a));
				cvLine( color_dst, pt1, pt2, CV_RGB(255,0,0), 2, 8 );

				bool found = false;
				for (int l = 0; l < (int)linelist2.size(); l++)
				{
					if ((rho < (linelist2[l].rho + MINSEP)) && (rho > (linelist2[l].rho - MINSEP)))
					{
						found = true;
						
						linelist2[l].rho = (linelist2[l].rho * linelist2[l].avgs + rho) / (linelist2[l].avgs + 1);
						linelist2[l].theta = (linelist2[l].theta * linelist2[l].avgs + theta) / (linelist2[l].avgs + 1);
						linelist2[l].avgs++;

						break;
					}
				}

				if (!found)
				{
					scrline temp = {line[0],line[1],1};
					linelist2.push_back(temp);
				}
			}

			//linelist2.c

			std::vector<diffs> difflist;

			std::sort(linelist.begin(), linelist.end());
			std::sort(linelist2.begin(), linelist2.end());

			for (int l = 0; l < (int)linelist2.size()-1; l++)
			{
				diffs temp = {linelist2[l+1].rho - linelist2[l].rho,l};
				difflist.push_back(temp);
			}
			std::sort(difflist.begin(), difflist.end());

			int diffavgxline = difflist[(difflist.size() - 1) / 2].i;
			float diffavgx = difflist[(difflist.size() - 1) / 2].diff;

			difflist.clear();

			for (int l = 0; l < (int)linelist.size()-1; l++)
			{
				diffs temp = {linelist2[l+1].rho - linelist2[l].rho,l};
				difflist.push_back(temp);
			}
			std::sort(difflist.begin(), difflist.end());
			int diffavgyline = difflist[(difflist.size() - 1) / 2].i;
			float diffavgy = difflist[(difflist.size() - 1) / 2].diff;





			for (int l = 0; l < (int)linelist2.size(); l++)
			{
				double a = cos(linelist2[l].theta), b = sin(linelist2[l].theta);
				double x0 = a*linelist2[l].rho, y0 = b*linelist2[l].rho;
				
				//double a = cos(theta), b = sin(theta);
				//double x0 = a*rho, y0 = b*rho;

				CvPoint pt1, pt2;
				pt1.x = cvRound(x0 + 5000*(-b));
				pt1.y = cvRound(y0 + 5000*(a));
				pt2.x = cvRound(x0 - 5000*(-b));
				pt2.y =	cvRound(y0 - 5000*(a));
				cvLine( color_dst, pt1, pt2, CV_RGB(0,0,255), 4, 8 );
			}

			//CvSize siz = { (int) diffavgx , (int)diffavgy };

			//IplImage* letter = cvCreateImage( siz, 8, 3 );

			for (int y = 0; y < 0 && (int)linelist.size(); y++)
				for (int x = 0; x < 0 && (int)linelist2.size(); x++)
				{
					
					//double xa = cos(linelist[y].theta)*linelist[y].rho,
					double ya = sin(linelist[y].theta)*linelist[y].rho;
					double xb = cos(linelist2[x].theta)*linelist2[x].rho;
					//double yb = sin(linelist2[x].theta)*linelist2[x].rho;

					CvPoint pt1,pt2,pt3,pt4;
					pt1.x = cvRound(xb - 25 + diffavgx / 2);
					pt1.y = cvRound(ya + 5 + diffavgy / 2);
					pt2.x = cvRound(xb + 10 + diffavgx / 2);
					pt2.y = cvRound(ya + 5 + diffavgy / 2);
					pt3.y = cvRound(ya + 5 + diffavgy / 2);
					pt4.y = cvRound(ya + 5 + diffavgy / 2);

					/*		//pt.x = 0, pt.y = 0;

					*/


					cvLine( color_dst, pt1, pt2, CV_RGB(255,0,255), 4, 8 );

					//int minx = 0;
					//int linemin = 255;

					double max = 0;
					CvScalar c;
					CvScalar clr = CV_RGB( 255, 0, 0 );

					for (pt3.x=pt2.x;pt3.x>pt1.x;pt3.x--)
					{
						c = cvGetAt(med,pt3.y,pt3.x);

						if (c.val[1] <= 60 && c.val[2] >= 160)
						{
							if (max < c.val[2] - c.val[1])
							{
								max = c.val[2] - c.val[1];
								pt4.x = pt3.x;
							}
						}

						/*if (c.val[0] > 145 && c.val[1] > 145)
							cvLine(src, pt3,pt3,CV_RGB(255,0,0));
						else
							cvLine(src, pt3,pt3,CV_RGB(0,255,0));
						

						if (max < c.val[2] - c.val[1])
						{
							max = c.val[2] - c.val[1];
							pt4.x = pt3.x;
						}*/
					}

					if (max > 0)
					{
						cvLine( color_dst, pt4, pt4, CV_RGB(255,0,0), 4, 8 );

						int lo_diff = atoi(argv[7]);
						int up_diff = 200;

						CvConnectedComp cc2;

						//cvFloodFill(src, pt4, clr, CV_RGB( lo_diff, lo_diff, lo_diff ),CV_RGB( up_diff, up_diff, up_diff ), &cc2, CV_FLOODFILL_FIXED_RANGE&CV_FLOODFILL_MASK_ONLY, NULL);//, ,cvScaleAll(0), cvScalarAll(0), cc2);

						/*while (cc2.area > atoi(argv[8]))
						{
							lo_diff--;
							cvFloodFill(src, pt4, clr, CV_RGB( lo_diff, lo_diff, lo_diff ),CV_RGB( up_diff, up_diff, up_diff ), &cc2, CV_FLOODFILL_FIXED_RANGE&CV_FLOODFILL_MASK_ONLY, NULL);//, ,cvScaleAll(0), cvScalarAll(0), cc2);
						}*/


						cvFloodFill(src, pt4, clr, CV_RGB( lo_diff, lo_diff, lo_diff ),CV_RGB( up_diff, up_diff, up_diff ), &cc2, CV_FLOODFILL_FIXED_RANGE +  CV_FLOODFILL_MASK_ONLY, mask);//, ,cvScaleAll(0), cvScalarAll(0), cc2);



						printf("%d,%d\n", mask->height, mask->width);
						//printf("%d,%d", cc2
					}
								
					/*int lo_diff = 8;
					int up_diff = 8;

					CvConnectedComp cc2;

					cvFloodFill(src, pt3, clr, CV_RGB( lo_diff, lo_diff, lo_diff ),CV_RGB( up_diff, up_diff, up_diff ), &cc2, 8, NULL);//, ,cvScaleAll(0), cvScalarAll(0), cc2);
					*/
					//pt3.x = minx;

					
					

					//for (int b=0;b>10;b++)
						
					

					/*cvGetRectSubPix(src, letter, pt2);
					cvNamedWindow( "Letter", 1 );
					cvShowImage( "Letter", letter );*/

					//cvWaitKey(0);
				}

			float avgytheta = linelist[diffavgyline].theta;
			float avgyrho = linelist[diffavgyline].rho;
			float avgxtheta = linelist2[diffavgxline].theta;
			float avgxrho = linelist2[diffavgxline].rho;

			printf("%d,%d\n", diffavgyline, diffavgxline);

			double xa = cos(avgytheta)*avgyrho, ya = sin(avgytheta)*avgyrho;
			double xb = cos(avgxtheta)*avgxrho, yb = sin(avgxtheta)*avgxrho;
		
			double x1 = xa - 2000*sin(avgytheta);
			double y1 = ya + 2000*cos(avgytheta);
			double x2 = xa + 2000*sin(avgytheta);
			double y2 = ya - 2000*cos(avgytheta);

			double x3 = xb - 2000*sin(avgxtheta);
			double y3 = yb + 2000*cos(avgxtheta);
			double x4 = xb + 2000*sin(avgxtheta);
			double y4 = yb - 2000*cos(avgxtheta);

			double denom = ((y4 - y3)*(x2 - x1)) - ((x4 - x3)*(y2 - y1));

			double nume_a = ((x4 - x3)*(y1 - y3)) - ((y4 - y3)*(x1 - x3));

			double nume_b = ((x2 - x1)*(y1 - y3)) - ((y2 - y1)*(x1 - x3));

			if(denom == 0.0f)
			{
				//Parallel lines, something has gone horribly wrong
				return 0;
			}

			double ua = nume_a / denom;
			double ub = nume_b / denom;

			double x_intersect = 0;
			double y_intersect = 0;

			if(ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f)
			{
				// Get the intersection point.
				x_intersect = x1 + ua*(x2 - x1);
				y_intersect = y1 + ua*(y2 - y1);

				CvPoint pt1;
				pt1.x = cvRound(x_intersect);
				pt1.y = cvRound(y_intersect);
				cvLine( color_dst, pt1, pt1, CV_RGB(255,0,255), 20, 8 );

				printf("Point %d,%d\n", pt1.x, pt1.y);

				CvPoint2D32f pt2;
				pt2.x = (float)(x_intersect + (diffavgx / 2));
				pt2.y = (float)(y_intersect + (diffavgy / 2));

				/*cvGetRectSubPix(src, letter, pt2);
				cvNamedWindow( "Letter", 1 );
				cvShowImage( "Letter", letter );
				char c = 0;
				scanf("%c", &c);
				if (c <= */
			}

			for (int y = -9; y <= 9; y++)
			for (int x = -13; x <= 13; x++)
			{
				CvPoint pt1;
				pt1.x = cvRound(x_intersect - x*diffavgx*sin(avgytheta));
				pt1.y = cvRound(y_intersect + y*diffavgy*cos(avgxtheta));
				cvLine( color_dst, pt1, pt1, CV_RGB(0,255,255), 20, 8 );
			}
			


			/*for (int y = diffavgyline; y < diffavgyline + 2 && (int)linelist.size(); y++)
				for (int x = diffavgxline; x < diffavgxline + 2 && (int)linelist2.size(); x++)
				{
					double xa = cos(linelist[y].theta)*linelist[y].rho, ya = sin(linelist[y].theta)*linelist[y].rho;
					double xb = cos(linelist2[x].theta)*linelist2[x].rho, yb = sin(linelist2[x].theta)*linelist2[x].rho;
				
					double x1 = xa - 2000*sin(linelist[y].theta);
					double y1 = ya + 2000*cos(linelist[y].theta);
					double x2 = xa + 2000*sin(linelist[y].theta);
					double y2 = ya - 2000*cos(linelist[y].theta);

					double x3 = xb - 2000*sin(linelist2[x].theta);
					double y3 = yb + 2000*cos(linelist2[x].theta);
					double x4 = xb + 2000*sin(linelist2[x].theta);
					double y4 = yb - 2000*cos(linelist2[x].theta);

					double denom = ((y4 - y3)*(x2 - x1)) -
                      ((x4 - x3)*(y2 - y1));

					double nume_a = ((x4 - x3)*(y1 - y3)) -
								   ((y4 - y3)*(x1 - x3));

					double nume_b = ((x2 - x1)*(y1 - y3)) -
								   ((y2 - y1)*(x1 - x3));

					if(denom == 0.0f)
					{
						//Parallel lines, something has gone horribly wrong
						continue;
					}

					double ua = nume_a / denom;
					double ub = nume_b / denom;

					if(ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f)
					{
						// Get the intersection point.
						double x_intersect = x1 + ua*(x2 - x1);
						double y_intersect = y1 + ua*(y2 - y1);

						CvPoint pt1;
						pt1.x = cvRound(x_intersect);
						pt1.y = cvRound(y_intersect);
						cvLine( color_dst, pt1, pt1, CV_RGB(255,0,255), 20, 8 );

						printf("Point %d,%d\n", pt1.x, pt1.y);

						CvPoint2D32f pt2;
						pt2.x = (float)(x_intersect + (diffavgx / 2));
						pt2.y = (float)(y_intersect + (diffavgy / 2));

					}
					
				}*/


						/*cvGetRectSubPix(src, letter, pt2);
						cvNamedWindow( "Letter", 1 );
						cvShowImage( "Letter", letter );
						char c = 0;
						scanf("%c", &c);
						if (c <= */


			for (int y = 0; y <  (int)linelist.size(); y++)
				for (int x = 0; x < (int)linelist2.size(); x++)
				{
					double xa = cos(linelist[y].theta)*linelist[y].rho, ya = sin(linelist[y].theta)*linelist[y].rho;
					double xb = cos(linelist2[x].theta)*linelist2[x].rho, yb = sin(linelist2[x].theta)*linelist2[x].rho;
				

					double x1 = xa - 2000*sin(linelist[y].theta);
					double y1 = ya + 2000*cos(linelist[y].theta);
					double x2 = xa + 2000*sin(linelist[y].theta);
					double y2 = ya - 2000*cos(linelist[y].theta);

					double x3 = xb - 2000*sin(linelist2[x].theta);
					double y3 = yb + 2000*cos(linelist2[x].theta);
					double x4 = xb + 2000*sin(linelist2[x].theta);
					double y4 = yb - 2000*cos(linelist2[x].theta);

					double denom = ((y4 - y3)*(x2 - x1)) -
                      ((x4 - x3)*(y2 - y1));

					double nume_a = ((x4 - x3)*(y1 - y3)) -
								   ((y4 - y3)*(x1 - x3));

					double nume_b = ((x2 - x1)*(y1 - y3)) -
								   ((y2 - y1)*(x1 - x3));

					if(denom == 0.0f)
					{
						//Parallel lines, something has gone horribly wrong
						continue;
					}

					double ua = nume_a / denom;
					double ub = nume_b / denom;

					if(ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f)
					{
						// Get the intersection point.
						double x_intersect = x1 + ua*(x2 - x1);
						double y_intersect = y1 + ua*(y2 - y1);

						CvPoint pt1;
						pt1.x = cvRound(x_intersect);
						pt1.y = cvRound(y_intersect);
						//cvLine( color_dst, pt1, pt1, CV_RGB(255,0,255), 4, 8 );

						CvPoint2D32f pt2;
						pt2.x = (float)(x_intersect + (diffavgx / 2));
						pt2.y = (float)(y_intersect + (diffavgy / 2));

						/*cvGetRectSubPix(src, letter, pt2);
						cvNamedWindow( "Letter", 1 );
						cvShowImage( "Letter", letter );
						char c = 0;
						scanf("%c", &c);
						if (c <= */
					}

					//cout << "Intesection at (" << x_intersect << ", " << y_intersect << ")" << endl;


					/*
					double xa = cos(linelist[y].theta)*linelist[y].rho, ya = sin(linelist[y].theta)*linelist[y].rho;
					double xb = cos(linelist2[x].theta)*linelist2[x].rho, yb = sin(linelist2[x].theta)*linelist2[x].rho;
					double ca = ya - tan(linelist[y].theta)*xa, cb = yb - tan(linelist2[x].theta)*xb;
					double gradient1 = (tan(linelist[y].theta) - tan(linelist2[x].theta));

					printf("g:%f %f c:%f %f\n", tan(linelist[y].theta), tan(linelist2[x].theta), ca, cb);

					double xcord = (cb - ca) / gradient1;
					double ycord = tan(linelist2[x].theta) * (xcord) + cb;

					printf("(%f,%f)%f=%f (%f,%f)%f=%f\n  %f, %f\n", xa,ya,linelist[y].theta,tan(linelist[y].theta), xb,yb,linelist2[x].theta,tan(linelist2[x].theta), xcord, ycord);

					CvPoint pt1;
					pt1.x = cvRound(x_intersect);
					pt1.y = cvRound(y_intersect);
					cvLine( color_dst, pt1, pt1, CV_RGB(255,0,255), 4, 8 );*/
				}
				
				
				

		}
		/*else
		{
			lines = cvHoughLines2( dst, storage, CV_HOUGH_PROBABILISTIC, 1, 3*CV_PI/180, atoi(argv[5]), atoi(argv[6]), atoi(argv[7]));
			for( i = 0; i < lines->total; i++ )
			{
				CvPoint* line = (CvPoint*)cvGetSeqElem(lines,i);
				
				cvLine( color_dst, line[0], line[1], CV_RGB(255,0,0), 3, 8 );
				cvLine( color_dst, line[0], line[0], CV_RGB(0,0,255), 4, 8 );
				cvLine( color_dst, line[1], line[1], CV_RGB(0,0,255), 4, 8 );
			}
		}*/

		/*for (int y = 0; y < src->height; y++)
		for (int x = 0; x < src->width; x++)
		{
			CvPoint xy = cvPoint(x,y);

			CvScalar c = cvGetAt(src, y, x);

			if (c.val[2] == 255)
				cvLine( color_dst, xy, xy, CV_RGB(0,0,0));
			else
				cvLine( color_dst, xy, xy, CV_RGB(255,255,255));
		}*/

        cvNamedWindow( "Source", 1 );
        cvShowImage( "Source", src );
		
        cvNamedWindow( "Med", 1 );
        cvShowImage( "Med", med );

		/*cvThreshold( src, med, atof(argv[7]), 255, CV_THRESH_BINARY_INV );
        cvNamedWindow( "Thresh", 1 );
        cvShowImage( "Thresh", med );*/

        cvNamedWindow( "Hough", 1 );
		

		//cvSaveImage("output4.jpg", color_dst);

		cvResize(color_dst, color_dst2);
        cvShowImage( "Hough", color_dst2 );

		

        cvWaitKey(0);
    }
	else
		printf("Unable to load image...\n");

	return 0;
}

